package com.hzh.audioflutter.my_audio_recorder

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap.Config
import android.media.MediaPlayer
import android.os.Build
import android.widget.Toast
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import io.flutter.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** MyAudioRecorderPlugin */
class MyAudioRecorderPlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private lateinit var applicationContext: Context
    private lateinit var result: Result
    private lateinit var mediaPlayer: MediaPlayer

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        applicationContext = flutterPluginBinding.applicationContext
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "my_audio_recorder")
        channel.setMethodCallHandler(this)
        // 注册广播
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            applicationContext.registerReceiver(
                recordStateReceiver, IntentFilter(RecordState.RECORD_BROADCAST_ACTION),
                Context.RECEIVER_EXPORTED
            )
        }
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android - ${android.os.Build.VERSION.RELEASE}")
        } else if (call.method == "startRecord") {
            result.success("start success")
            startRecord()
        } else if (call.method == "continueRecord") {
            result.success("continue success")
            continueRecord()
        } else if (call.method == "pauseRecord") {
            result.success("pause success")
            pauseRecord()
        } else if (call.method == "stopRecord") {
            this.result = result
//            result.success("stop success")
            stopRecord()
        }  else if (call.method == "playAudio") {
            result.success("play success")
            playAudio(call.arguments.toString())
        } else {
            result.notImplemented()
        }
    }

    private fun playAudio(audioPath: String) {
        android.util.Log.e("TAG_ME", "播放音频路径 $audioPath")
        mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource(audioPath)
        mediaPlayer.prepareAsync()
        mediaPlayer.setOnPreparedListener {
            mediaPlayer.start()
        }
    }

    private fun startRecord() {
        doAction(RecordState.RECORD_ACTION_START)
    }

    private fun continueRecord() {
        doAction(RecordState.RECORD_ACTION_CONTINUE)
    }

    private fun pauseRecord() {
        doAction(RecordState.RECORD_ACTION_PAUSE)
    }

    private fun stopRecord() {
        doAction(RecordState.RECORD_ACTION_STOP)
    }

    private fun doAction(action: String) {
        val intent = Intent(applicationContext, AudioRecordService::class.java)
        intent.putExtra(RecordState.RECORD_ACTION, action)
        applicationContext.startService(intent)
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            applicationContext.startForegroundService(intent)
//            Log.e("TAG_ME", "doAction---------startForegroundService")
//        } else {
//        }
    }

    private val recordStateReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == RecordState.RECORD_BROADCAST_ACTION) {
                val action = intent.getStringExtra(RecordState.RECORD_BROADCAST_ACTION)
                if (action == RecordState.RECORD_ACTION_OVER) {
                    // 停止录音，返回结果
                    val filePath = intent.getStringExtra(RecordState.RECORD_BROADCAST_FILE_PATH)
                    result.success(filePath)
                }
            }
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
        applicationContext.unregisterReceiver(recordStateReceiver)
    }
}
